package bag

import (
	"log"
	"errors"
)

func BuildBag(maxcap int) (*Bag,error){
	b:=&Bag{
		Max: maxcap,
		Used: 0,
	}
	
	node,err:=BMan.PopId()
	if err!=nil{
		log.Println("segment fault from bag pool")
		return nil,err
	}
	b.Items,err=createBlist(node)
	
	return b,err
}

func (b *Bag)DeleteBag() error{
	return b.Items.DeleteList()
}

// AddItem adds an item to the bag if there is space
func (b *Bag) AddItem(id uint16) error {
	if b.Used >= b.Max {
		return errors.New("bag is full")
	}
	if err := b.Items.PushBack(id); err != nil {
		return err
	}
	b.Used++
	return nil
}

// RemoveItem removes an item from the bag by ID
func (b *Bag) RemoveItem(id uint16) error {
	if err := b.Items.Remove(id); err != nil {
		return err
	}
	b.Used--
	return nil
}

// GetItem retrieves an item from the bag by ID
func (b *Bag) GetItem(id uint16) (*Item, error) {
	current := b.Items.root.Next
	for current != 0 {
		item, err := BMan.GetItem(current)
		if err != nil {
			return nil, err
		}
		if item.Id == id {
			return item, nil
		}
		current = BMan.GetItemNext(current)
	}
	return nil, errors.New("item not found")
}

// UpdateItem updates an existing item's properties
func (b *Bag) UpdateItem(id uint16, updateFn func(*Item) error) error {
	item, err := b.GetItem(id)
	if err != nil {
		return err
	}
	return updateFn(item)
}

// ListItems returns all items in the bag
func (b *Bag) ListItems() ([]*Item, error) {
	var items []*Item
	current := b.Items.root.Next
	for current != 0 {
		item, err := BMan.GetItem(current)
		if err != nil {
			return nil, err
		}
		items = append(items, item)
		current = BMan.GetItemNext(current)
	}
	return items, nil
}
